package com.scut.statistics_website.endpoint;

import com.alibaba.fastjson.JSONObject;
import com.scut.statistics_website.model.Demand;
import com.scut.statistics_website.model.Supplier;
import com.scut.statistics_website.service.*;
import io.lettuce.core.dynamic.annotation.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.websocket.Session;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;

@RestController
public class HttpEndpoint {
    private static final Logger sysLogger = Logger.getLogger("sysLog");

    @Autowired
    private MessageService messageService;

    @Autowired
    private DemandService demandService;

    @Autowired
    private SupplierService supplierService;

    @Autowired
    private RelationshipService relationshipService;

    @Autowired
    private StatisticsService statisticsService;

    @PostMapping(value = "demand")
    public void getNewDemand(@RequestParam(value="id") String id, @RequestParam(value="lon") float lon, @RequestParam(value = "lat") float lat) {
        List<Session> userSessions = WebSocketEndpoint.getUserSessions();
        if(userSessions.size() > 0) {
            for(Session session : userSessions) {
                try {
                    session.getBasicRemote().sendText("Demand comes" + id + lon +lat);
                }
                catch (IOException e){
                    sysLogger.info("error in session");
                }
            }
        }
    }



    @PostMapping("/demand/add")
    public void addDemand(@RequestBody JSONObject jsonObject) {
//        Set<Map.Entry<String, Object>> entries = jsonObject.entrySet();
//        for (Map.Entry<String, Object> entry : entries) {
//            System.out.println(entry.getKey() + "--" + entry.getValue());
//        }
        jsonObject.put("type", "add_demand");
        messageService.sendMessage(jsonObject.toJSONString());
    }

    @PostMapping("/demand/delete")
    public void deleteDemand(@RequestBody String demandId) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type", "delete_demand");
        jsonObject.put("id", demandId);
        sysLogger.info("----------------------------delete_demand " + demandId + " ------------------------------");
        sysLogger.info(jsonObject.toJSONString());
        messageService.sendMessage(jsonObject.toJSONString());
    }


    @PostMapping("/supplier/add")
    public void addSupplier(@RequestBody JSONObject jsonObject) {
        jsonObject.put("type", "add_supplier");
        messageService.sendMessage(jsonObject.toJSONString());
    }

    @PostMapping("/supplier/delete")
    public void deleteSupplier(@RequestBody JSONObject jsonObject) {
        jsonObject.put("type", "delete_supplier");
        sysLogger.info("received");
        messageService.sendMessage(jsonObject.toJSONString());
    }

    //接收多对多关系
    @PostMapping("/relationship/add")
    public void addRelationship(@RequestBody JSONObject jsonObject){
        jsonObject.put("type", "init_relationship");
        messageService.sendMessage(jsonObject.toJSONString());
    }

    //抢单
    @PostMapping("/relationship/update")
    public void updateRelationship(@RequestBody JSONObject jsonObject){
        jsonObject.put("type", "select_demand");
        sysLogger.info("----------------------------select------------------------------");
        messageService.sendMessage(jsonObject.toJSONString());
    }

    //接收 round_ended, 清空 relationships
    @PostMapping("/relationship/delete")
    public void clearRelationship(){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type", "round_ended");
        messageService.sendMessage(jsonObject.toJSONString());
    }

    @GetMapping("/relationship/restore")
    public String restoreRelationship(){
        ArrayList<Demand> deamnds = new ArrayList<>();
        ArrayList<String> demandIds = demandService.getCachedDemands();
        for (String demandId : demandIds) {
            deamnds.add(demandService.getDemand(demandId));
        }
        ArrayList<Supplier> suppliers = new ArrayList<>();
        ArrayList<String> supplierIds = supplierService.getCachedSuppliers();
        for (String supplierId : supplierIds) {
            suppliers.add(supplierService.getSupplier(supplierId));
        }
        ArrayList<String> relationships = relationshipService.getRelationships();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("demands", deamnds);
        jsonObject.put("suppliers", suppliers);
        jsonObject.put("relationships", relationships);
        return jsonObject.toJSONString();
    }

    @GetMapping("/statistics/real_time")
    public String getRealTimePerformance() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("avg_answer_time", statisticsService.getAvgAnswerTime());
        jsonObject.put("success_rate", statisticsService.getSuccessRate());
        jsonObject.put("expired_rate", statisticsService.getExpiredRate());
        return jsonObject.toJSONString();
    }

    @GetMapping("/statistics/answer_time")
    public String getRealTimeAnswerTime() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("answer_times", statisticsService.getAvgAnswerTimes());
        return jsonObject.toJSONString();
    }

    @GetMapping("/statistics/success_rate")
    public String getRealTimeSuccessRate() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("success_rates", statisticsService.getSuccessRates());
        return jsonObject.toJSONString();
    }
}
